#!/bin/bash
# ========================================
# 一键部署脚本 - 部署前端、后端和数据库
# ========================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 脚本路径
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_ROOT=$(cd "$SCRIPT_DIR/.." && pwd)

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 打印标题
print_title() {
    local title=$1
    echo ""
    print_message "$CYAN" "========================================="
    print_message "$CYAN" "  $title"
    print_message "$CYAN" "========================================="
    echo ""
}

# 打印横幅
print_banner() {
    clear
    print_message "$GREEN" "╔════════════════════════════════════════╗"
    print_message "$GREEN" "║                                        ║"
    print_message "$GREEN" "║     若依系统一键部署脚本 v1.0         ║"
    print_message "$GREEN" "║     RuoYi Auto Deploy Script           ║"
    print_message "$GREEN" "║                                        ║"
    print_message "$GREEN" "╚════════════════════════════════════════╝"
    echo ""
}

# 检查必要的工具
check_tools() {
    print_title "🔍 检查系统环境"
    
    local missing_tools=()
    
    # 检查Java
    if ! command -v java &> /dev/null; then
        missing_tools+=("java")
        print_message "$RED" "❌ Java 未安装"
    else
        print_message "$GREEN" "✅ Java: $(java -version 2>&1 | head -n 1)"
    fi
    
    # 检查Maven
    if ! command -v mvn &> /dev/null; then
        missing_tools+=("maven")
        print_message "$RED" "❌ Maven 未安装"
    else
        print_message "$GREEN" "✅ Maven: $(mvn -version | head -n 1 | awk '{print $3}')"
    fi
    
    # 检查Node.js
    if ! command -v node &> /dev/null; then
        missing_tools+=("nodejs")
        print_message "$RED" "❌ Node.js 未安装"
    else
        print_message "$GREEN" "✅ Node.js: $(node -v)"
    fi
    
    # 检查npm
    if ! command -v npm &> /dev/null; then
        missing_tools+=("npm")
        print_message "$RED" "❌ npm 未安装"
    else
        print_message "$GREEN" "✅ npm: $(npm -v)"
    fi
    
    # 检查MySQL客户端
    if ! command -v mysql &> /dev/null; then
        missing_tools+=("mysql-client")
        print_message "$RED" "❌ MySQL客户端 未安装"
    else
        print_message "$GREEN" "✅ MySQL客户端 已安装"
    fi
    
    # 如果有缺失的工具，显示安装提示
    if [ ${#missing_tools[@]} -gt 0 ]; then
        echo ""
        print_message "$RED" "⚠️  缺少以下工具: ${missing_tools[*]}"
        print_message "$YELLOW" "请先安装缺失的工具后再运行此脚本"
        exit 1
    fi
    
    print_message "$GREEN" "\n✅ 所有必要工具已安装"
}

# 显示部署选项
show_deploy_options() {
    print_title "📋 部署选项"
    
    print_message "$BLUE" "请选择部署方式:"
    echo ""
    print_message "$YELLOW" "  1. 完整部署 (数据库 + 后端 + 前端)"
    print_message "$YELLOW" "  2. 仅部署数据库"
    print_message "$YELLOW" "  3. 仅部署后端"
    print_message "$YELLOW" "  4. 仅部署前端"
    print_message "$YELLOW" "  5. 部署后端 + 前端 (跳过数据库)"
    print_message "$YELLOW" "  6. 退出"
    echo ""
}

# 部署数据库
deploy_database() {
    print_title "📊 部署数据库"
    
    if [ -f "$SCRIPT_DIR/init_database.sh" ]; then
        bash "$SCRIPT_DIR/init_database.sh" full
    else
        print_message "$RED" "❌ 数据库初始化脚本不存在"
        exit 1
    fi
}

# 部署后端
deploy_backend() {
    print_title "🚀 部署后端服务"
    
    if [ -f "$SCRIPT_DIR/deploy_backend.sh" ]; then
        bash "$SCRIPT_DIR/deploy_backend.sh"
    else
        print_message "$RED" "❌ 后端部署脚本不存在"
        exit 1
    fi
}

# 部署前端
deploy_frontend() {
    print_title "🎨 部署前端应用"
    
    if [ -f "$SCRIPT_DIR/deploy_frontend.sh" ]; then
        bash "$SCRIPT_DIR/deploy_frontend.sh"
    else
        print_message "$RED" "❌ 前端部署脚本不存在"
        exit 1
    fi
}

# 完整部署
full_deploy() {
    print_title "🎉 开始完整部署"
    
    print_message "$CYAN" "部署流程："
    print_message "$CYAN" "  1️⃣  初始化数据库"
    print_message "$CYAN" "  2️⃣  编译并部署后端"
    print_message "$CYAN" "  3️⃣  构建并部署前端"
    echo ""
    
    read -p "确认开始完整部署? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_message "$YELLOW" "取消部署"
        return
    fi
    
    # Step 1: 数据库
    deploy_database
    
    # Step 2: 后端
    deploy_backend
    
    # Step 3: 前端
    deploy_frontend
    
    show_final_info
}

# 部署后端和前端
deploy_backend_frontend() {
    print_title "🚀 部署后端和前端"
    
    print_message "$CYAN" "部署流程："
    print_message "$CYAN" "  1️⃣  编译并部署后端"
    print_message "$CYAN" "  2️⃣  构建并部署前端"
    echo ""
    
    read -p "确认开始部署? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_message "$YELLOW" "取消部署"
        return
    fi
    
    # Step 1: 后端
    deploy_backend
    
    # Step 2: 前端
    deploy_frontend
    
    show_final_info
}

# 显示最终信息
show_final_info() {
    print_title "🎉 部署完成"
    
    print_message "$GREEN" "所有服务已成功部署！"
    echo ""
    
    print_message "$BLUE" "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print_message "$BLUE" "📋 服务信息"
    print_message "$BLUE" "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    # 数据库信息
    print_message "$CYAN" "📊 数据库:"
    print_message "$YELLOW" "  • 地址: localhost:3306"
    print_message "$YELLOW" "  • 数据库: ry-vue"
    print_message "$YELLOW" "  • 用户: root"
    echo ""
    
    # 后端信息
    print_message "$CYAN" "🚀 后端服务:"
    print_message "$YELLOW" "  • 地址: http://localhost:8080"
    print_message "$YELLOW" "  • 日志: $PROJECT_ROOT/logs/ruoyi-admin.jar.log"
    print_message "$YELLOW" "  • 管理: ./ry.sh {start|stop|restart|status}"
    echo ""
    
    # 前端信息
    print_message "$CYAN" "🎨 前端应用:"
    print_message "$YELLOW" "  • 地址: http://localhost"
    print_message "$YELLOW" "  • 目录: /usr/share/nginx/html/ruoyi"
    print_message "$YELLOW" "  • 配置: /etc/nginx/conf.d/ruoyi.conf"
    echo ""
    
    # 默认账号
    print_message "$CYAN" "👤 默认账号:"
    print_message "$YELLOW" "  • 管理员: admin / admin123"
    echo ""
    
    print_message "$BLUE" "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    print_message "$GREEN" "🌐 访问地址: http://localhost"
    print_message "$GREEN" "📖 API文档: http://localhost/dev-api/swagger-ui.html"
    echo ""
    
    # 检查服务状态
    print_message "$CYAN" "🔍 服务状态检查..."
    echo ""
    
    # 检查后端
    if curl -s http://localhost:8080 > /dev/null 2>&1; then
        print_message "$GREEN" "✅ 后端服务运行正常"
    else
        print_message "$RED" "❌ 后端服务未响应"
    fi
    
    # 检查前端
    if curl -s http://localhost > /dev/null 2>&1; then
        print_message "$GREEN" "✅ 前端服务运行正常"
    else
        print_message "$RED" "❌ 前端服务未响应"
    fi
    
    echo ""
    print_message "$PURPLE" "🎊 恭喜！系统部署成功！"
}

# 显示帮助信息
show_help() {
    print_banner
    
    cat << EOF
用法: $0 [选项]

选项:
  --help, -h          显示此帮助信息
  --full              完整部署（数据库+后端+前端）
  --database          仅部署数据库
  --backend           仅部署后端
  --frontend          仅部署前端
  --services          部署后端和前端（跳过数据库）
  --check             仅检查系统环境

示例:
  $0                  # 交互式菜单
  $0 --full           # 完整部署
  $0 --backend        # 仅部署后端
  $0 --check          # 检查环境

EOF
}

# 主菜单循环
main_menu() {
    while true; do
        show_deploy_options
        read -p "请选择 (1-6): " choice
        
        case $choice in
            1)
                full_deploy
                ;;
            2)
                deploy_database
                ;;
            3)
                deploy_backend
                ;;
            4)
                deploy_frontend
                ;;
            5)
                deploy_backend_frontend
                ;;
            6)
                print_message "$GREEN" "👋 再见！"
                exit 0
                ;;
            *)
                print_message "$RED" "❌ 无效选择，请重新输入"
                sleep 2
                clear
                print_banner
                ;;
        esac
        
        if [ "$choice" != "6" ]; then
            echo ""
            print_message "$CYAN" "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            read -p "按回车键返回主菜单..." 
            clear
            print_banner
        fi
    done
}

# 主函数
main() {
    # 处理命令行参数
    case "${1:-}" in
        --help|-h)
            show_help
            exit 0
            ;;
        --check)
            print_banner
            check_tools
            exit 0
            ;;
        --full)
            print_banner
            check_tools
            full_deploy
            exit 0
            ;;
        --database)
            print_banner
            check_tools
            deploy_database
            exit 0
            ;;
        --backend)
            print_banner
            check_tools
            deploy_backend
            exit 0
            ;;
        --frontend)
            print_banner
            check_tools
            deploy_frontend
            exit 0
            ;;
        --services)
            print_banner
            check_tools
            deploy_backend_frontend
            exit 0
            ;;
        "")
            # 无参数，显示交互式菜单
            print_banner
            check_tools
            main_menu
            ;;
        *)
            print_message "$RED" "❌ 未知选项: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 捕获Ctrl+C
trap 'echo ""; print_message "$YELLOW" "⚠️  部署已取消"; exit 130' INT

# 运行主函数
main "$@"

